package cn.kow.kmall.controller.system;

import cn.kow.kmall.common.enums.KmallResultEnum;
import cn.kow.kmall.controller.BaseController;
import cn.kow.kmall.core.exception.ServiceException;
import cn.kow.kmall.core.response.KmallResult;
import cn.kow.kmall.system.entity.SysConfig;
import cn.kow.kmall.admin.pojo.dto.ConfigQueryDTO;
import cn.kow.kmall.system.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: lijun
 * @Description:
 * @Date: Created in 2019-10-29 17:04
 * @Modified By:
 */
@Slf4j
@RestController
@RequestMapping("/config")
public class SysConfigController extends BaseController {

    @Autowired
    private SysConfigService configService;

    /**
     * 新增参数配置
     * @param config  参数配置
     * @return 结果
     */
    @PostMapping(value = "/add")
    public KmallResult add(@Validated @RequestBody SysConfig config) {
        config.setCreateBy(currentUser().getUsername());
        configService.save(config);
        return KmallResult.success();
    }

    /**
     * 删除参数配置
     * @param id    参数配置ID
     * @return 结果
     */
    @DeleteMapping("/{id}")
    public KmallResult remove(@PathVariable Long id) {
        configService.remove(id);
        return KmallResult.success();
    }

    /**
     * 修改参数配置
     * @param config  参数配置
     * @return 结果
     */
    @PostMapping(value = "/edit")
    public KmallResult edit(@Validated @RequestBody SysConfig config) {
        config.setUpdateBy(currentUser().getUsername());
        configService.update(config);
        return KmallResult.success();
    }

    /**
     * 根据参数配置ID获取详细信息
     * @param id    岗位ID
     * @return 结果
     */
    @GetMapping(value = "/{id}")
    public KmallResult getInfo(@PathVariable Long id) {
        SysConfig config = configService.getById(id);
        if (null == config) {
            throw new ServiceException(KmallResultEnum.DAO_NOT_FOUND);
        }
        return KmallResult.success(config);
    }

    /**
     * 获取参数配置列表
     */
    @PostMapping("/list")
    public KmallResult list(@RequestBody ConfigQueryDTO queryDTO) {
        Page<SysConfig> page = configService.listByPage(queryDTO);
        return KmallResult.success().put("rows", page.getContent())
                .put("total", page.getTotalElements());
    }
}

